package com.pt25.base.dep.redis.aspect;

import com.pt25.base.dep.redis.RedisService;
import com.pt25.base.util.JsonUtil;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class QueryCacheAspect extends BaseCacheAspect {
    @Resource
    private RedisService redisService;

    @Around("@annotation(com.pt25.base.dep.redis.aspect.QueryCache)")
    public Object queryCache(ProceedingJoinPoint pjp) throws Throwable {
        Method method = getMethod(pjp);
        //1、获取注解
        QueryCache queryCache = method.getAnnotation(QueryCache.class);
        //2、获取缓存key
        String dataCacheKey = getDataCacheKey(pjp, method, queryCache.cacheKey(), queryCache.value().getName());
        //3、查询缓存
        if (null != dataCacheKey) {
            RedissonClient redissonClient = redisService.getRedissonClient(queryCache.redisName());
            Object cacheObj = redissonClient.getBucket(dataCacheKey, new StringCodec()).get();
            if (null != cacheObj) {
                return JsonUtil.toBean((String) cacheObj, method.getReturnType());
            }
        }
        return pjp.proceed();
    }
}
